package com.shed.demo.listener;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContextEvent;

public class DbStarter extends org.h2.server.web.DbStarter {
	private Connection conn;

	public void contextInitialized(ServletContextEvent servletContextEvent) {
		super.contextInitialized(servletContextEvent);

		// 初始化数据库
		conn = super.getConnection();
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery("select count(*) from users");
			if (rs.next() && rs.getInt(1) > 0) {
				return;
			} else {
				st.execute("RUNSCRIPT FROM '"
						+ servletContextEvent.getServletContext()
								.getRealPath("/WEB-INF/classes/resources/dbschema.sql") + "' CHARSET 'UTF-8';");
			}

			rs.close();
			st.close();
		} catch (SQLException e) {
			try {
				Statement st = conn.createStatement();
				st.execute("RUNSCRIPT FROM '"
						+ servletContextEvent.getServletContext()
								.getRealPath("/WEB-INF/classes/resources/dbschema.sql") + "' CHARSET 'UTF-8';");
				st.close();
			} catch (SQLException ex) {
				ex.printStackTrace();
			}
		}
	}
}
